<template>
	<div>
		<el-dialog title="添加类型" :visible.sync="editorVisible" width="30%" :before-close="closeEditorClassify" @open="opendEnd">
			<el-form :model="classifyList" ref="addClassify" label-width="100px">
        <el-form-item label="类型名称" prop="classifyName" :rules="[
              { required: true, message: '请输入类型名称', trigger: 'blur' },
            ]">
        	<el-input type="text" v-model="classifyList.classifyName" placeholder="请输入用户名" clearable></el-input>
        </el-form-item>

				<el-form-item label="类型图片" prop="classifyImg">
          <el-input v-show="false" v-model="classifyList.imgState"/>
					<!-- <el-input type="text" v-model="classifyList.classifyImg" placeholder="请输入持有人姓名" clearable></el-input> -->
				  <el-upload
				    class="upload-demo"
				    ref="upload"
				    list-type="picture"
				    action=""
				    :limit="1"
            :on-change="imgVaildata"
				    :auto-upload="false"
				    :on-remove="handleRemove"
				    :before-upload="beforeUploadHandle"
				    :http-request="handleUploadForm"
				    >
				    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
				    <!-- <el-button style="margin-left: 10px;" size="small"  @click="submitUpload">上传到服务器</el-button> -->
				    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
				  </el-upload>
				  <!-- <input type="file" name="photo"><br> -->
				</el-form-item>

        <el-form-item label="文章内容" v-if="showArticle">
          <el-input type="textarea" v-model="classifyList.articleDetail" clearable></el-input>
        </el-form-item>

        <el-form-item label="显示状态" prop="indexShow" :rules="[
              { required: true, message: '请选择是否启用', trigger: 'blur' },
            ]">
          <el-switch
            v-model="classifyList.onstatus" @change="onstatus(classifyList.onstatus)"
            active-text="启用" inactive-text="禁用">
          </el-switch>
        </el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="closeEditorClassify">取 消</el-button>
				<el-button type="primary" @click="submitUpload('addClassify')">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		name: "",
		props: ["editorVisible","editorObj"],
		data() {
			return {
        showArticle:false,
				classifyList: {
					classifyName: "",
          classifyImg:"",
          classifyType:0,
          articleDetail:"",
          //以下两个变量用于判断用户状态
          indexShow:0,
          onstatus:false,
          //判断有无图片
          imgState:null,
				},
			}
		},
		methods: {
    //清空图片方法
    clearFiles () {
        this.$refs['upload'].clearFiles();
    },
    //验证图片是否为空
    imgVaildata(file, fileList){
        var self = this
        console.log('vue 图片上传钩子函数')
        self.classifyList.imgState=file.name
        console.log(self.classifyList.imgState)
        if(file.name==null || file.name==""){
          self.classifyList.imgState=null
        }
    },
      /* */
    //判断表单数据是否为空
     //并提交数据
    submitUpload(params) {
      console.log("触发判断事件")
      var self = this
      this.$refs[params].validate((valid) => {
        console.log(self.classifyList.imgState)
     	if (valid) {
         if(self.classifyList.imgState==null || self.classifyList.imgState==""){
           self.addClassify(params)
           console.log(1)
         }else{
            self.$refs.upload.submit();
           console.log(2)
         }
     	} else {
     		console.log('error submit!!');
     		return false;
     	}
     });
    },
     //触发删除事件
     handleRemove(file, fileList) {
       console.log("触发删除事件")
       if(file){
         this.classifyList.imgState=""
       }
       console.log(file, fileList);
     },
     /* */
     //查询当前添加的是否是文章，文章可以添加文章内容
     typeJudge(judgeType){
        if(judgeType===1){
          this.showArticle=true
        }else{
          this.showArticle=false
          this.classifyList.articleDetail=""
        }
     },
      //需要等待dialog 打开完毕后 在金数据渲染
      //设置权限下拉框的默认值
      opendEnd(){
        // console.log(this.$props.editorObj)
        // console.log(this.$props.editorObj.indexShow)
        // console.log(this.$props.editorObj.onstatus)
        // console.log()
        this.classifyList.classifyId = this.$props.editorObj.classifyId
        this.classifyList.classifyName = this.$props.editorObj.classifyName
        this.classifyList.classifyImg = this.$props.editorObj.classifyImg
        this.classifyList.indexShow = this.$props.editorObj.indexShow
        this.classifyList.classifyType=  this.$props.editorObj.classifyType
        this.classifyList.articleDetail=this.$props.editorObj.articleDetail
        this.onstatus(this.$props.editorObj.indexShow)
        this.typeJudge(this.$props.editorObj.classifyType)
      },
      //设置是否显示状态
      onstatus(indexShow){
        // console.log(indexShow)
        if(indexShow===1){

          this.classifyList.onstatus=true
        }else if(indexShow===0){
          this.classifyList.onstatus=false
        }
        // console.log(this.manager.onstatus)
        // console.log(this.manager.status)
      },
      //清除文本框数据，返回相对应文本框的值
      clearData(){
          this.classifyList={
            classifyId:0,
            classifyName: "",
            classifyType:0,
            articleDetail:"",
            //以下两个变量用于判断用户状态
            indexShow:0,
            onstatus:false,
          }
          this.showArticle=false
          this.clearFiles()
      },
      //设置关闭添加页面方法
			closeEditorClassify() {
        // this.opendEnd()
        this.clearFiles()
				this.$parent.editorVisible = false
			},
      //上传文件前执行的方法,判断文件格式
      beforeUploadHandle(file) {
        console.log("执行上传前方法")
        if (
            file.type !== "image/png" &&
            file.type !== "image/jpeg"
        ) {
          this.$message.error("只支持.jpg、.jpeg、.jpe、.png文件！");
          return false;
        }
      },

      //执行添加方法
      handleUploadForm(param) {
        console.log(param)
        console.log(JSON.stringify(this.classifyList))
        let self = this
        var onlineManager = JSON.parse(sessionStorage.getItem("manager"))
        var page = sessionStorage.getItem("page")
        this.typeJudge(this.classifyList.classifyType)
        //通过显示状态进行显示数据传值
        if(self.classifyList.onstatus===true){
          self.classifyList.indexShow=1
        }else{
          self.classifyList.indexShow=0
        }
        // 检测输入的数据中是否存在空格
        var classifyName = this.classifyList.classifyName
        var ifArticle = this.classifyList.classifyType
        if(ifArticle!=1){
          this.classifyList.articleDetail=""
        }
        if(classifyName.split(" ").length==1){
          let formData = new FormData()
          // 在formData中加入我们需要的参数
          formData.append('file', param.file)
          formData.append('classify', JSON.stringify(this.classifyList))
          console.log("开始向后端发送请求")
          console.log(this.classifyList)
          // 向后端发送数据
          self.$http.post('/api/CakeShop/DataManage/udpClassifyWithImg', formData).then((res) => {
            console.log(123123)
            // if (res.status === 200) {
            //   thisInfo.$message.success('修改信息成功')
            // } else {
            //   thisInfo.$message.success('修改信息失败')
            // }
            // thisInfo.formFileList = []
            // thisInfo.uploadFormFileList = []
            console.log(res)
            //判断数据是否存在
            if(res.data.exist===0){
              if (res.data.udpSuccNum>0) {
                self.$message({
                  message: res.data.msg,
                  type: 'success',
                  onClose: function() {
                    //添加完毕后清楚文本框中内容
                    self.clearData()
                    //关闭修改界面
                    self.closeEditorClassify()
                    //添加完数据返回首页
                    self.$parent.getMemberList(page)
                  }
                });
              }else{
                self.$message({
                  duration: 1500,
                  message: res.data.msg,
                  type: "error",
                  onClose: function() {
                    self.loading = false;
                  },
                });
              }
            }else{
              self.$message({
              	duration: 1500,
              	message: res.data.msg,
              	type: "error",
              	onClose: function() {
              		self.loading = false;
              	},
              });
            }
          })
        }else{
          self.$message({
            duration: 1500,
            message: "用户名中存在非法字符空格!",
            type: "error",
            onClose: function() {
              self.loading = false;
            },
          });
        }
      },




      //执行添加方法
			addClassify(params) {
				var self = this
				this.$refs[params].validate((valid) => {
					if (valid) {
						var onlineManager = JSON.parse(sessionStorage.getItem("manager"))
            var page = sessionStorage.getItem("page")
            this.typeJudge(this.classifyList.classifyType)
            //通过显示状态进行显示数据传值
            if(self.classifyList.onstatus===true){
              self.classifyList.indexShow=1
            }else{
              self.classifyList.indexShow=0
            }
            // 检测输入的数据中是否存在空格
            var classifyName = this.classifyList.classifyName
            if(classifyName==null){
              classifyName=''
            }
            console.log("==========")
            console.log(this.classifyList)
            if(classifyName.split(" ").length==1){
              self.$http({
                url: "/api/CakeShop/DataManage/udpClassify",
                method: "post",
                // headers: {
                // 	token: manager.token
                // },
                data: {
                  classifyId:self.classifyList.classifyId,
                  classifyName:self.classifyList.classifyName,
                  classifyType:self.classifyList.classifyType,
                  indexShow: self.classifyList.indexShow,
                  articleDetail:self.classifyList.articleDetail
                },
              }).then(function(res) {
                // console.log(res)
                //判断数据是否存在
                if(res.data.exist===0){
                  if (res.data.udpSuccNum>0) {
                    self.$message({
                      message: res.data.msg,
                      type: 'success',
                      onClose: function() {
                        //添加完毕后清楚文本框中内容
                        self.clearData()
                        //关闭修改界面
                        self.closeEditorClassify()
                        //添加完数据返回首页
                        self.$parent.getMemberList(page)
                      }
                    });
                  }else{
                    self.$message({
                      duration: 1500,
                      message: res.data.msg,
                      type: "error",
                      onClose: function() {
                        self.loading = false;
                      },
                    });
                  }
                }else{
                  self.$message({
                  	duration: 1500,
                  	message: res.data.msg,
                  	type: "error",
                  	onClose: function() {
                  		self.loading = false;
                  	},
                  });
                }
              })
            }else{
              self.$message({
                duration: 1500,
                message: "用户名中存在非法字符空格!",
                type: "error",
                onClose: function() {
                  self.loading = false;
                },
              });
            }
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
		}
	}
</script>
<style>
</style>
